package cn.monkey.family.server.domain.uc.org.role;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.uc.org.role.OrgRole;
import cn.monkey.family.data.uc.role.Role;
import cn.monkey.family.server.domain.uc.role.BeforeRoleDeletedEventListener;

import java.util.Objects;
import java.util.Optional;

public class OrgRoleRelChecker implements BeforeRoleDeletedEventListener {

    protected final OrgRoleRepository orgRoleRepository;

    public OrgRoleRelChecker(OrgRoleRepository orgRoleRepository) {
        this.orgRoleRepository = orgRoleRepository;
    }

    @Override
    public Result<Void> beforeRoleDeleted(RequestContext requestContext, Role role) {
        Optional<OrgRole> orgRoleOptional = this.orgRoleRepository.findByRoleId(role.getId());
        if (orgRoleOptional.isEmpty()) {
            return Results.fail("ORG_ROLE_REL_NOT_FOUND");
        }
        if (!Objects.equals(requestContext.getOrgId(), orgRoleOptional.get().getOrgId())) {
            return Results.fail("ORG_ROLE_REL_NOT_MATCH");
        }
        return Results.ok();
    }
}
